package com.aheizi.oa.view.action;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.jsp.PageContext;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.aheizi.oa.base.BaseAction;
import com.aheizi.oa.domain.Department;
import com.aheizi.oa.service.DepartmentService;
import com.aheizi.oa.util.DepartmentUtils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ModelDriven;

@Controller
@Scope("prototype")
public class DepartmentAction extends BaseAction<Department>{
	
	private Long parentId;
	
	public String list() throws Exception{
		List<Department> departmentList = null;
		
		if(parentId == null){ //顶级部门列表
			departmentList = departmentService.findTopList();
		}else{//子部门列表
			departmentList = departmentService.findChildren(parentId);
			Department parent = departmentService.getById(parentId);
			ActionContext.getContext().put("parent", parent);
		}
		
		ActionContext.getContext().put("departmentList", departmentList);
		return "list";
	}
	
	public String delete() throws Exception{
		departmentService.delete(model.getId());
		return "toList";
	}
	
	public String add() throws Exception{
		//封装信息到对象中
		System.out.println(parentId);
		Department parent = departmentService.getById(parentId);
		model.setParent(parent);
		
		//保存
		departmentService.save(model);
		return "toList";
	}
	
	public String addUI() throws Exception{
		//准备数据 departmentList
		List<Department> topList = departmentService.findTopList();
		List<Department> departmentList = DepartmentUtils.getAllDepartments(topList);
		ActionContext.getContext().put("departmentList", departmentList);
		return "saveUI";
	}
	
	public String edit() throws Exception{
		//1.从数据库取出原对象
		Department department = departmentService.getById(model.getId());
		
		//2.设置修改的属性
		department.setName(model.getName());
		department.setDescription(model.getDescription());
		department.setParent(departmentService.getById(parentId));
		
		//3.更新到数据库中
		departmentService.update(department);
		
		return "toList";
	}
	
	public String editUI() throws Exception{
		//准备数据 departmentList 给 select
		List<Department> topList = departmentService.findTopList();
		List<Department> departmentList = DepartmentUtils.getAllDepartments(topList);
		ActionContext.getContext().put("departmentList", departmentList);
		
		//准备回显数据
		Department department = departmentService.getById(model.getId());
		ActionContext.getContext().getValueStack().push(department);
		if(department.getParent() != null){
			parentId = department.getParent().getId();
		}
		return "saveUI";
	}
	
	//-----
	public Long getParentId() {
		return parentId;
	}

	public void setParentId(Long parentId) {
		this.parentId = parentId;
	}

}
